package org.ddd.orderdemo.shared.event.spring.listener;

import org.ddd.orderdemo.shared.event.spring.BizEvent;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

public class EventListenerService {

    @EventListener({BizEvent.class })
    public void onEvent(BizEvent event) {
        System.out.println("收到事件:" + event);
    }

    @Async
    @EventListener({ BizEvent.class })
    public void asyncHandle(BizEvent event) {
        System.out.println("异步处理，收到事件:" + event);
        System.out.println("异步处理，开始执行业务操作生成关键日志。发送时间：" + event.getTimestamp());
    }

    /**
     *  TransactionPhase.AFTER_COMMIT 事务提交后，再由监听器去处理事件。事件处理，不影响事务。
     * @param event
     */
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT,value = { BizEvent.class })
    public void handle(BizEvent event) {
        System.out.println("事务提交后，收到事件:" + event);
        System.out.println("事务提交后，开始执行业务操作给用户发送短信。发送时间：" + event.getTimestamp());
    }




}
